﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using DataCenter.Component.Adapter;
using DataCenter.Component.Calculator;
using DataCenter.Component.Processor;
using DataCenter.Component.Source;
using DataCenter.Interface.Model;
using DataCenter.Share;

namespace DateCenter.UpdateTool
{
	public class CenterUpdate : UpdateBase
	{
		public override bool UpdateObjects(SqlCommand command0, SqlCommand command1)
		{
			try
			{
				Logger.GetInstance().Info("\t开始更新对象...");

				string commandString = @"SELECT * FROM SYS_OBJ_INFO Info RIGHT OUTER JOIN SYS_OBJ_CONFIG Config
										ON Info.G__SCADA_ID = Config.G__SCADA_ID";
				command0.CommandText = commandString;
				command0.CommandType = CommandType.Text;
				using (SqlDataReader reader = command0.ExecuteReader())
				{
					while (reader.Read())
					{                        
						Logger.GetInstance().DebugFormat("\t\t正在更新对象 {0}", reader["G__SCADA_ID"].ToString());
						InsertObject(command1, reader);
					}
				}

				commandString = @"SELECT * FROM SYS_OBJ_INFO Info INNER JOIN SYS_OBJ_CALC Calc
								ON Info.G__SCADA_ID = Calc.G__SCADA_ID";
				command0.CommandText = commandString;
				command0.CommandType = CommandType.Text;
				using (SqlDataReader reader = command0.ExecuteReader())
				{
					while (reader.Read())
					{
						Logger.GetInstance().DebugFormat("\t\t正在更新对象 {0}", reader["G__SCADA_ID"].ToString());
						InsertObject(command1, reader);
					}
				}

				Logger.GetInstance().Info("\t对象更新成功。");
				return true;
			}
			catch (Exception ex)
			{
				Logger.GetInstance().Error("\t对象更新失败", ex);
				return false;
			}
		}
		public override bool UpdateTypes(SqlCommand command0, SqlCommand command1)
		{
			try
			{
				Logger.GetInstance().Info("\t开始更新对象类型...");

				string commandString = @"SELECT DISTINCT G__SCADA_TYPE FROM SYS_OBJ_INFO Info INNER JOIN SYS_OBJ_CONFIG Config
										ON Info.G__SCADA_ID = Config.G__SCADA_ID";

				command0.CommandText = commandString;
				command0.CommandType = CommandType.Text;
				using (SqlDataReader reader = command0.ExecuteReader())
				{
					while (reader.Read())
					{
						int objectType = Convert.ToInt32(reader["G__SCADA_TYPE"]);
						Logger.GetInstance().DebugFormat("\t\t正在更新对象类型 {0}", objectType);

						if (IsRecordExist(command1, "ObjectType", "TypeId", objectType))
						{
							int newId = SearchMaxId(command1, "ObjectType", "TypeId") + 1;
							Logger.GetInstance().DebugFormat("\t\t\t将对象类型\"{0}\"更新为\"{1}\"", objectType, newId);
							UpdateObjectValue(command1, "ObjectType", objectType, -1 * newId);
							objectType = newId;
						}
							
						commandString = "INSERT INTO ObjectType(TypeId, TypeName) VALUES(@TypeId, @TypeName)";
						command1.CommandText = commandString;
						command1.CommandType = CommandType.Text;
						command1.Parameters.AddWithValue("@TypeId", objectType);
						command1.Parameters.AddWithValue("@TypeName", "类型" + objectType);
						command1.ExecuteNonQuery();
						command1.Parameters.Clear();
					}
				}

				Logger.GetInstance().Info("\t对象类型更新成功。");
				return true;
			}
			catch (Exception ex)
			{
				Logger.GetInstance().Error("\t对象类型更新失败", ex);
				return false;
			}
		}
		public override bool UpdateSourceComponents(SqlCommand command0, SqlCommand command1)
		{
			try
			{
				Logger.GetInstance().Info("\t开始更新数据源对象...");

				string commandString = "SELECT * FROM SYS_SCADA_SOURCE";

				command0.CommandText = commandString;
				command0.CommandType = CommandType.Text;
				using (SqlDataReader reader = command0.ExecuteReader())
				{
					while (reader.Read())
					{
						int sourceId = Convert.ToInt32(reader["G__SOURCE_ID"]);
						string sourceType = reader["G__SOURCE_NAME"].ToString();                       
						string connectionString = reader["G__SOURCE_CONN"].ToString();

						if (string.Compare(sourceType, "ScadaSampleInf.ScadaSourceSql") == 0)
						{
							Logger.GetInstance().DebugFormat("\t\t正在更新数据源 {0}", sourceId);

							SqlConnectionStringBuilder cnStrBuilder = new SqlConnectionStringBuilder(connectionString);
							SqlSourceEntity entity = new SqlSourceEntity();
							entity.ComponentId = sourceId;
							entity.ComponentName = "数据源" + sourceId;
							entity.ComponentType = ComponentTypes.Source;
							entity.AssemblyName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "DataCenter.Component.dll");
							entity.TypeName = "DataCenter.Component.Source.SqlSourceEntity";
							entity.DataSource = cnStrBuilder.DataSource;
							entity.InitialCatalog = cnStrBuilder.InitialCatalog;
							entity.IntegratedSecurity = cnStrBuilder.IntegratedSecurity;
							entity.UserId = cnStrBuilder.UserID;
							entity.Password = cnStrBuilder.Password;
							entity.ComponentConfig = entity.ToXml().OuterXml;
							entity.Insert(command1);

							if (sourceId != entity.ComponentId)
							{
								Logger.GetInstance().DebugFormat("\t\t\t将数据源编号\"{0}\"更新为\"{1}\"", sourceId, entity.ComponentId);
								UpdateObjectValue(command1, "BindingSourceId", sourceId, -1 * entity.ComponentId);
							}
						}
						else
						{
							string msg = "G__SOURCE_ID=" + sourceId + ";G__SOURCE_NAME=" + sourceType + ";G__SOURCE_CONN=" + connectionString;
							Logger.GetInstance().ErrorFormat("\t\t数据源{0}无法执行更新，无法解析类型名称\"{1}\"", sourceId, sourceType);
							Logger.GetInstance().Error(msg);
						}
					}
				}

				Logger.GetInstance().Info("\t数据源对象更新成功。");
				return true;
			}
			catch (Exception ex)
			{
				Logger.GetInstance().Error("\t数据源对象更新失败：" + ex.Message);
				return false;
			}
		}
		public override bool UpdateAdapterComponents(SqlCommand command0, SqlCommand command1)
		{
			try
			{
				Logger.GetInstance().Info("\t开始更新数据适配器对象...");
				
				string commandString = "SELECT * FROM SYS_SCADA_PLUGIN";
				command0.CommandText = commandString;
				command0.CommandType = CommandType.Text;

				DataTable dt = new DataTable();
				using (SqlDataAdapter adapter = new SqlDataAdapter(command0))
					adapter.Fill(dt);

				foreach (DataRow row in dt.Rows)
				{
					int pluginId = Convert.ToInt32(row["G__PLUGIN_ID"]);
					string pluginName = row["G__PLUGIN_NAME"].ToString().Trim();
					string pluginClass = row["G__PLUGIN_CLASS"].ToString().Trim();

					ComponentEntity entity = null;
					if (string.Compare(pluginClass, "ScadaSampleInf.ScadaSamplePluginVert") == 0)
					{
						Logger.GetInstance().DebugFormat("\t\t正在更新数据适配器 {0}", pluginId);

						entity = new VerticalAdapterEntity();
						entity.ComponentId = pluginId;
						entity.ComponentName = pluginName;
						entity.ComponentType = ComponentTypes.Adapter;
						entity.AssemblyName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "DataCenter.Component.dll");
						entity.TypeName = "DataCenter.Component.Adapter.VerticalAdapterEntity";
					}
					else if (string.Compare(pluginClass, "ScadaSampleInf.ScadaSamplePluginHorz") == 0)
					{
						Logger.GetInstance().DebugFormat("\t\t正在更新数据适配器 {0}", pluginId);

						entity = new HorizontalAdapterEntity();
						entity.ComponentId = pluginId;
						entity.ComponentName = pluginName;
						entity.ComponentType = ComponentTypes.Adapter;
						entity.AssemblyName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "DataCenter.Component.dll");
						entity.TypeName = "DataCenter.Component.Adapter.HorizontalAdapterEntity";
					}
					else
					{
						string msg = "G__PLUGIN_ID=" + pluginId + ";G__PLUGIN_NAME=" + pluginName + ";G__PLUGIN_CLASS=" + pluginClass;
						Logger.GetInstance().ErrorFormat("\t\t数据适配器{0}无法执行更新，无法解析类型名称\"{1}\"", pluginId, pluginClass);
						Logger.GetInstance().Error(msg);
						continue;
					}

					commandString = "SELECT G__SOURCE_SQL FROM SYS_OBJ_CONFIG WHERE G__PLUGIN_ID = " + pluginId;
					command0.CommandText = commandString;
					command0.CommandType = CommandType.Text;
					using (SqlDataReader reader = command0.ExecuteReader())
					{
						while (reader.Read())
						{
							string sqlString = reader["G__SOURCE_SQL"].ToString().Trim();

							if (entity is VerticalAdapterEntity)
							{
								((VerticalAdapterEntity)entity).SqlString = sqlString;
								if (sqlString.StartsWith("SELECT", StringComparison.OrdinalIgnoreCase))
								{
									int fromIndex = sqlString.IndexOf("FROM", StringComparison.OrdinalIgnoreCase);
									if (fromIndex >= 0)
									{
										string selectClause = sqlString.Substring(6, fromIndex - 6).Trim();
										string[] fieldArray = selectClause.Split(new char[] { ',' });
										if (fieldArray.Length >= 2)
										{
											((VerticalAdapterEntity)entity).TimeField = fieldArray[0].Trim();
											((VerticalAdapterEntity)entity).ValueField = fieldArray[1].Trim();
										}
									}
								}
							}
							else if (entity is HorizontalAdapterEntity)
							{
								((HorizontalAdapterEntity)entity).SqlString = sqlString;
							}

							entity.ComponentConfig = entity.ToXml().OuterXml;
							entity.Insert(command1);

							if (pluginId != entity.ComponentId)
							{
								Logger.GetInstance().DebugFormat("\t\t\t将适配器编号\"{0}\"更新为\"{1}\"", pluginId, entity.ComponentId);
								UpdateObjectValue(command1, "BindingAdapterId", pluginId, -1 * entity.ComponentId);
							}
						}
					}
				}


				Logger.GetInstance().Info("\t数据适配器对象更新成功。");
				return true;
			}
			catch (Exception ex)
			{
				Logger.GetInstance().Error("\t数据适配器对象更新失败：" + ex.Message);
				return false;
			}
		}
		public override bool UpdateProcessComponents(SqlCommand command0, SqlCommand command1)
		{
			try
			{
				Logger.GetInstance().Info("\t开始更新数据处理器对象...");

				string commandString = "SELECT * FROM SYS_SCADA_INTERPOLATION";
				command0.CommandText = commandString;
				command0.CommandType = CommandType.Text;

				DataTable dt = new DataTable();
				using (SqlDataAdapter adapter = new SqlDataAdapter(command0))
					adapter.Fill(dt);

				foreach (DataRow row in dt.Rows)
				{
					int patchId = Convert.ToInt32(row["G__PATCH_ID"]);
					string patchName = row["G__PATCH_NAME"].ToString();

					Logger.GetInstance().DebugFormat("\t\t正在更新数据处理器 {0}", patchId);

					InterpolateProcessorEntity entity = new InterpolateProcessorEntity();
					entity.ComponentId = patchId;
					entity.ComponentName = "处理器" + patchId;
					entity.ComponentType = ComponentTypes.Processor;
					entity.AssemblyName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "DataCenter.Component.dll");
					entity.TypeName = "DataCenter.Component.Processor.InterpolateProcessorEntity";

					if (string.Compare(patchName, "SCADAPatch.LinearPatch") == 0)
					{
						entity.InterpolateType = InterpolateTypes.Linear;
					}
					else if (string.Compare(patchName, "SCADAPatch.SwitchPatch") == 0)
					{
						entity.InterpolateType = InterpolateTypes.Switch;
					}
					else
					{
						string msg = "G__PATCH_ID=" + patchId + ";G__PATCH_NAME=" + patchName;
						Logger.GetInstance().ErrorFormat("\t\t数据处理器{0}无法执行更新，无法解析类型名称\"{1}\"", patchId, patchName);
						Logger.GetInstance().Error(msg);
						continue;
					}

					entity.ForwardSearchMinutes = 0;
					entity.BackwardSearchMinutes = 0;
					entity.IsRealValueAsDefault = true;
					entity.ComponentConfig = entity.ToXml().OuterXml;
					entity.Insert(command1);

					if (patchId != entity.ComponentId)
					{
						Logger.GetInstance().DebugFormat("\t\t\t将处理器编号\"{0}\"更新为\"{1}\"", patchId, entity.ComponentId);
						UpdateObjectValue(command1, "BindingProcessorId", patchId, -1 * entity.ComponentId);
					}
				}

				Logger.GetInstance().Info("\t数据源对象更新成功。");
				return true;
			}
			catch (Exception ex)
			{
				Logger.GetInstance().Error("\t数据源对象更新失败：" + ex.Message);
				return false;
			}
		}
		public override bool UpdateCalculateComponents(SqlCommand command0, SqlCommand command1)
		{
			try
			{
				Logger.GetInstance().Info("\t开始更新数据计算器对象...");

				string commandString = "SELECT * FROM SYS_OBJ_CALC";
				command0.CommandText = commandString;
				command0.CommandType = CommandType.Text;

				using(SqlDataReader reader = command0.ExecuteReader())
				{
					while (reader.Read())
					{
						int objectId = Convert.ToInt32(reader["G__SCADA_ID"]);
						string patchName = reader["G__CALC_PATCH"].ToString();

						Logger.GetInstance().DebugFormat("\t\t正在更新数据计算器 {0}", objectId);

						ArithmeticCalculatorEntity entity = new ArithmeticCalculatorEntity();
						entity.ComponentId = objectId;
						entity.ComponentName = "计算器" + objectId;
						entity.ComponentType = ComponentTypes.Calculator;
						entity.AssemblyName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "DataCenter.Component.dll");
						entity.TypeName = "DataCenter.Component.Calculator.ArithmeticCalculatorEntity";
						entity.ComponentConfig = entity.ToXml().OuterXml;
						entity.Insert(command1);

						Logger.GetInstance().DebugFormat("\t\t\t将对象\"{0}\"的计算器编号更新为\"{1}\"", objectId, entity.ComponentId);

						commandString = "UPDATE [Object] SET [BindingCalculatorId]={0} WHERE [ObjectId]={1}";
						command1.CommandText = string.Format(commandString, -1 * entity.ComponentId, objectId);
						command1.CommandType = CommandType.Text;
						command1.ExecuteNonQuery();
					}
				}

				Logger.GetInstance().Info("\t数据源对象更新成功。");
				return true;
			}
			catch (Exception ex)
			{
				Logger.GetInstance().Error("\t数据源对象更新失败：" + ex.Message);
				return false;
			}
		}
		public override bool UpdateSettings(SqlCommand command0, SqlCommand command1)
		{
			try
			{
				Logger.GetInstance().Info("\t开始更新数据中心配置...");

				int startIndex = 0, endIndex = 0, monthStep = 1;

				string commandString = "SELECT * FROM SYS_GLOBAL_CONFIG";
				command0.CommandText = commandString;
				command0.CommandType = CommandType.Text;
				using (SqlDataReader reader = command0.ExecuteReader())
				{
					if (reader.Read())
					{
						startIndex = Convert.ToInt32(reader["START_TIME_INDEX"]);
						endIndex = Convert.ToInt32(reader["END_TIME_INDEX"]);
						monthStep = Convert.ToInt32(reader["SPLIT_MONTH_COUNT"]);
					}
				}

				commandString = "UPDATE TableIndexSetting SET SplitMonthStep = {0}, StartTableIndex = {1}, EndTableIndex = {2}";
				command1.CommandText = string.Format(commandString, monthStep, startIndex, endIndex);
				command1.CommandType = CommandType.Text;
				command1.ExecuteNonQuery();

				Logger.GetInstance().Info("\t数据中心配置更新成功。");
				return true;
			}
			catch (Exception ex)
			{
				Logger.GetInstance().Error("\t数据中心配置更新失败：" + ex.Message);
				return false;
			}
		}
		public override bool UpdateValues(SqlCommand command0, SqlCommand command1)
		{
			try
			{
				Logger.GetInstance().Info("\t开始导入数据中心历史数据...");

				TableSetting setting = TableSetting.GetInstance();
				setting.Initialize(command1);

				for (int i = setting.StartTableIndex; i <= setting.EndTableIndex; i += setting.SplitMonthStep)
				{
					setting.CreateTable(command1, i);

					string commandString = "SELECT * FROM TBL_SCADA_" + i;
					command0.CommandText = commandString;
					command0.CommandType = CommandType.Text;
					using (SqlDataReader reader = command0.ExecuteReader())
					{
						while (reader.Read())
						{
							byte[] bytes = (byte[])reader["G__BLOB_DATA"];
							Array.Resize<byte>(ref bytes, bytes.Length + 1);
							Array.Copy(bytes, 0, bytes, 1, bytes.Length - 1);
							bytes[0] = 0x1;                            

							BinaryRecord record = new BinaryRecord();
							record.ObjectId = Convert.ToInt32(reader["G__OBJ_ID"]);
							record.ValueTime = Convert.ToDateTime(reader["G__OBJ_TIME"]);
							record.ValueType = Convert.ToInt32(reader["G__VALUE_TYPE"]);

							Binary binary = new DayBinary(bytes);
							record.BinaryValue = binary;

							record.UpdateImportTime();
							record.UpdateInterpolateTime();

							record.CreateRecord(command1);
						}
					}
				}

				Logger.GetInstance().Info("\t导入数据中心历史数据成功。");
				return true;
			}
			catch (Exception ex)
			{
				Logger.GetInstance().Error("\t导入数据中心历史数据失败：" + ex.Message);
				return false;
			}
		}

		private bool InsertObject(SqlCommand command, SqlDataReader reader)
		{
			bool loadResult = true;

			int objectId;
			object oValue = reader["G__SCADA_ID"];
			if (oValue == null || oValue == DBNull.Value || string.IsNullOrEmpty(oValue.ToString()))
				loadResult = Logger.GetInstance().Error("\t\t\tG__SCADA_ID字段存在NULL值");
			if (!int.TryParse(oValue.ToString(), out objectId))
				loadResult = Logger.GetInstance().ErrorFormat("\t\t\tG__SCADA_ID字段值\"{0}\"无效", oValue);

			int objectType;
			oValue = reader["G__SCADA_TYPE"];
			if (oValue == null || oValue == DBNull.Value || string.IsNullOrEmpty(oValue.ToString()))
				loadResult = Logger.GetInstance().Error("\t\t\t对象\"{0}\"的G__SCADA_TYPE字段存在NULL值");
			if (!int.TryParse(oValue.ToString(), out objectType))
				loadResult = Logger.GetInstance().ErrorFormat("\t\t\t对象\"{0}\"的G__SCADA_TYPE字段值\"{1}\"无效", objectId, oValue);

			string objectName = "对象" + objectId;
			oValue = reader["G__SCADA_NAME"];
			if (oValue == null || oValue == DBNull.Value || string.IsNullOrEmpty(oValue.ToString()))
				Logger.GetInstance().WarnFormat("\t\t\t对象\"{0}\"的G__SCADA_NAME字段为空，自动重命名为\"{1}\"", objectId, objectName);
			else objectName = oValue.ToString().Trim();

			bool isVirtual = false;
			string objectKey = "";
			int sourceId = -1, adapterId = -1, processId = -1, calculatorId = -1;
			float defaultValue = 0.0f;
			if (objectId < 16777216)
			{                
				oValue = reader["G__SCADA_KEY"];
				if (oValue == null || oValue == DBNull.Value || string.IsNullOrEmpty(oValue.ToString()))
					loadResult = Logger.GetInstance().ErrorFormat("\t\t\t对象\"{0}\"的G__SCADA_KEY字段为空", objectId);
				objectKey = oValue.ToString().Trim();
				
				oValue = reader["G__SOURCE_ID"];
				if (oValue == null || oValue == DBNull.Value || string.IsNullOrEmpty(oValue.ToString()))
					Logger.GetInstance().WarnFormat("\t\t\t对象\"{0}\"的G__SOURCE_ID字段存在NULL值", objectId);
				if (!int.TryParse(oValue.ToString(), out sourceId))
					loadResult = Logger.GetInstance().ErrorFormat("\t\t\t对象\"{0}\"的G__SOURCE_ID字段值\"{1}\"无效", objectId, oValue);
				
				oValue = reader["G__PLUGIN_ID"];
				if (oValue == null || oValue == DBNull.Value || string.IsNullOrEmpty(oValue.ToString()))
					Logger.GetInstance().WarnFormat("\t\t\t对象\"{0}\"的G__PLUGIN_ID字段存在NULL值", objectId);
				if (!int.TryParse(oValue.ToString(), out adapterId))
					loadResult = Logger.GetInstance().ErrorFormat("\t\t\t对象\"{0}\"的G__PLUGIN_ID字段值\"{1}\"无效", objectId, oValue);

				oValue = reader["G__PATCH_ID"];
				if (oValue == null || oValue == DBNull.Value || string.IsNullOrEmpty(oValue.ToString()))
					Logger.GetInstance().WarnFormat("\t\t\t对象\"{0}\"的G__PATCH_ID字段存在NULL值", objectId);
				if (!int.TryParse(oValue.ToString(), out processId))
					loadResult = Logger.GetInstance().ErrorFormat("\t\t\t对象\"{0}\"的G__PATCH_ID字段值\"{1}\"无效", objectId, oValue);
				
				oValue = reader["G__DEFAULT_VALUE"];
				if (oValue == null || oValue == DBNull.Value || string.IsNullOrEmpty(oValue.ToString()))
					Logger.GetInstance().WarnFormat("\t\t\t对象\"{0}\"的G__DEFAULT_VALUE字段存在NULL值", objectId);
				if (!float.TryParse(oValue.ToString(), out defaultValue))
					Logger.GetInstance().WarnFormat("\t\t\t对象\"{0}\"的G__DEFAULT_VALUE字段值\"{1}\"无效", objectId, oValue);
			}
			else
			{
				oValue = reader["G__SCADA_KEY"];
				if (oValue == null || oValue == DBNull.Value || string.IsNullOrEmpty(oValue.ToString()))
					loadResult = Logger.GetInstance().ErrorFormat("\t\t\t对象\"{0}\"的G__SCADA_KEY字段为空", objectId);
				objectKey = oValue.ToString().Trim();

				isVirtual = true;
			}

			if (loadResult)
			{
				if (IsRecordExist(command, "Object", "ObjectId", objectId))
				{
					int newId = ObjectEntity.SearchMaxId(command) + 1;
					Logger.GetInstance().DebugFormat("\t\t\t将对象编号\"{0}\"更新为\"{1}\"", objectId, newId);
					objectId = newId;
				}

				ObjectEntity entity = new ObjectEntity();
				entity.ObjectId = objectId;
				entity.ObjectType = objectType;
				entity.ObjectName = objectName;
				entity.ObjectKey = objectKey;
				entity.BindingSourceId = sourceId;
				entity.BindingAdapterId = adapterId;
				entity.BindingProcessorId = processId;
				entity.BindingCalculatorId = -1;
				entity.IsVirtual = isVirtual;
				entity.DefaultValue = defaultValue;
				entity.Unit = 1.0f;
				entity.Create(command);
			}

			return loadResult;
		}
		private int SearchMaxId(SqlCommand command, string tableName, string columnName)
		{
			string commandString = "SELECT MAX([{1}]) FROM [{0}]";
			command.CommandText = string.Format(commandString, tableName, columnName);
			command.CommandType = CommandType.Text;
			object oValue = command.ExecuteScalar();
			if (oValue == null || oValue == DBNull.Value) return 0;
			return Convert.ToInt32(oValue);
		}
		private int UpdateObjectValue(SqlCommand command, string columnName, object value0, object value1)
		{
			string commandString = "UPDATE [Object] SET [{0}]={2} WHERE [{0}]={1}";
			command.CommandText = string.Format(commandString, columnName, value0, value1);
			command.CommandType = CommandType.Text;
			return command.ExecuteNonQuery();            
		}
		private bool IsRecordExist(SqlCommand command, string tableName, string columnName, object value)
		{
			string commandString = "SELECT [{1}] FROM [{0}] WHERE [{1}] = ";
			if (value is string || value is DateTime)
				commandString += "'{2}'";
			else commandString += "{2}";
			command.CommandText = string.Format(commandString, tableName, columnName, value);
			command.CommandType = CommandType.Text;
			object oValue = command.ExecuteScalar();
			return ((oValue != null) && (oValue != DBNull.Value));
		}
	}
}
